// bluetoothManager.js
class BluetoothManager {
	constructor() {
		this.deviceId = '';
		this.serviceId = '0000ff00-0000-1000-8000-00805f9b34fb'; // Blufi服务UUID
		this.writeCharId = '0000ff01-0000-1000-8000-00805f9b34fb'; // 写特征值
		this.notifyCharId = '0000ff02-0000-1000-8000-00805f9b34fb'; // 通知特征值
		this.mtu = 20; // 默认MTU
	}

	// 初始化蓝牙适配器
	init() {
		return new Promise((resolve, reject) => {
			uni.openBluetoothAdapter({
				success: (res) => {
					console.log('蓝牙适配器初始化成功', res);
					this.startDiscovery();
					resolve(res);
				},
				fail: (err) => {
					console.error('初始化失败', err);
					reject(err);
				}
			});
		});
	}

	// 开始搜索设备
	startDiscovery() {
		uni.startBluetoothDevicesDiscovery({
			success: (res) => {
				console.log('开始搜索设备', res);
				this.listenDiscovery();
			},
			fail: (err) => {
				console.error('搜索失败', err);
			}
		});
	}

	// 监听发现设备
	listenDiscovery() {
		uni.onBluetoothDeviceFound((devices) => {
			// const espDevices = devices.devices.filter(device =>
			// 	device.name && device.name.startsWith('ESP32')
			// );
			// if (espDevices.length > 0) {
			// 	this.deviceId = espDevices[0].deviceId;
			// 	uni.stopBluetoothDevicesDiscovery();
			// 	this.connectDevice();
			// }
			console.log("数据是", devices);
		});
	}

	// 连接设备
	connectDevice() {
		uni.createBLEConnection({
			deviceId: this.deviceId,
			success: (res) => {
				console.log('连接成功', res);
				this.getServices();
			},
			fail: (err) => {
				console.error('连接失败', err);
			}
		});
	}

	// 获取服务
	getServices() {
		uni.getBLEDeviceServices({
			deviceId: this.deviceId,
			success: (res) => {
				console.log('发现服务', res);
				this.listenNotify();
				this.setMTU();
			}
		});
	}

	// 监听通知
	listenNotify() {
		uni.notifyBLECharacteristicValueChange({
			deviceId: this.deviceId,
			serviceId: this.serviceId,
			characteristicId: this.notifyCharId,
			success: () => {
				uni.onBLECharacteristicValueChange((res) => {
					this.handleData(res.value);
				});
			}
		});
	}

	// 设置MTU
	setMTU() {
		uni.setBLEMTU({
			deviceId: this.deviceId,
			mtu: 512,
			success: (res) => {
				this.mtu = res.mtu;
			}
		});
	}

	// 发送数据
	write(data) {
		const buffer = new ArrayBuffer(data.length);
		const view = new Uint8Array(buffer);
		for (let i = 0; i < data.length; i++) {
			view[i] = data[i];
		}

		uni.writeBLECharacteristicValue({
			deviceId: this.deviceId,
			serviceId: this.serviceId,
			characteristicId: this.writeCharId,
			value: buffer,
			success: () => {
				console.log('写入成功:', data);
			},
			fail: (err) => {
				console.error('写入失败', err);
			}
		});
	}

	// 处理接收数据
	handleData(buffer) {
		const view = new Uint8Array(buffer);
		console.log('收到数据:', view);

		// 根据Blufi协议解析数据
		// 这里需要实现具体的数据解析逻辑
	}

	// 发送WiFi配置
	sendWifiConfig(ssid, password) {
		// 构造Blufi数据帧（需要根据协议实现）
		const frame = this.buildBlufiFrame(ssid, password);

		// 分包发送（考虑MTU限制）
		const chunkSize = this.mtu - 3; // 3字节头
		for (let i = 0; i < frame.length; i += chunkSize) {
			const chunk = frame.slice(i, i + chunkSize);
			this.write(chunk);
		}
	}

	// 构造Blufi数据帧（示例）
	buildBlufiFrame(ssid, password) {
		const data = [];
		// 协议头
		data.push(0x01); // Type: WiFi配置
		data.push(0x00); // 帧控制
		// SSID长度
		data.push(ssid.length);
		// SSID数据
		for (let i = 0; i < ssid.length; i++) {
			data.push(ssid.charCodeAt(i));
		}
		// Password长度
		data.push(password.length);
		// Password数据
		for (let i = 0; i < password.length; i++) {
			data.push(password.charCodeAt(i));
		}
		return data;
	}
}

export default new BluetoothManager();